<template>
  <view>
    <view class="order" v-if="list.length">
      <u-card
        :title="cardTitle(order)"
        :sub-title="cardSubTitle(order)"
        v-for="order in list"
        :key="'order-' + keyname + order.id"
        :foot-style="footStyle"
      >
        <view class="" slot="body">
          <!-- <view class="u-body-item u-flex u-row-between u-border-bottom"> -->
          <!-- {{ cardBody(order) }} -->
          <view
            class="u-body-item u-flex u-border-bottom"
            v-for="product in order.orderItemList"
            :key="'product-' + product.id"
          >
            <!-- {{ OrderItemImg(item) }} -->
            <!-- {{ item }} -->
            <view class="left">
              <view class="img">
                <img :src="OrderItemImg(product.productId)" alt="" />
              </view>
              <view class="content">
                <view class="naem">
                  {{ product.productName }}
                </view>
                <view class="number"> x {{ product.num }} </view>
                <view class="props">
                  {{ product.saleAttrValueArray }}
                </view>
              </view>
            </view>
            <view class="right">
              <view class="price"> ￥ {{ product.realAmount }} </view>
            </view>
          </view>
          <view class="u-body-item u-flex u-row-between">
            <view class="left"> 备注 </view>
            <view class="right">
              <view class="place_holder" v-if="order.remark">{{
                order.remark
              }}</view>

              <view class="place_holder" v-else>无</view>
            </view>
          </view>
          <view class="u-body-item u-flex u-row-between">
            <view class="left">总价</view>
            <view class="left"> {{ order.realAmount }} 元 </view>
          </view>
          <view class="u-body-item u-flex u-row-between">
            <view class="left">日期</view>
            <view class="left"> {{ order.createTime }}</view>
          </view>
        </view>
        <view class="" slot="foot">
          <!-- <u-icon name="chat-fill" size="34" color="" label="30评论"></u-icon> -->
          <view class="foot_btn" v-if="order.orderStatus != -1">
            <button
              class="btn_to_pay"
              v-if="order.orderStatus == 0"
              @tap="handlerGoPay(order)"
            >
              去付款
            </button>
            <button
              class="btn_cancel mr-10"
              v-if="order.orderStatus == 0"
              @tap="handlerCancel(order)"
            >
              取消订单
            </button>
            <button
              class="over"
              @tap="handlerOverOrder(order)"
              v-if="order.orderStatus > 1 && order.confirmStatus == 0"
            >
              确认送达
            </button>
            <button
              class="moreOne"
              @tap="handlerMoreOne(order)"
              v-if="order.orderStatus != -1"
            >
              再来一单
            </button>
            <button
              class="commit mr-10"
              v-if="order.orderStatus == 4 || order.confirmStatus == 1"
              @tap="handlerCommit(order)"
            >
              查看评价
            </button>
            <button
              class="after_sale"
              v-if=" order.confirmStatus == 1  && order.orderStatus == 4"
              @tap="handerApplyAfterSale(order)"
            >
              申请售后

            </button>
            <button
              class="after_sale"
              v-if=" order.confirmStatus == 1 && order.orderStatus <= -2"
              @tap="handerApplyAfterSale(order)"
            >
              查看售后
            </button>
          </view>
        </view>
      </u-card>
      <view class="end">没有更多订单记录了..</view>
    </view>

    <view class="order_no" v-else>
      <view class="up">
        还没有订单, 现在就去<text class="highlight" @tap="handlerGoToMenu()"
          >点单</text
        >犒劳一下自己叭.
      </view>
      <view class="down">
        <u-icon name="clock" size="50rpx"></u-icon>
        <text>订单记录只能显示到6个月之前的哦.</text>
      </view>
    </view>

    <u-toast ref="tips"></u-toast>
    <!-- <u-toa></u-toa/st> -->
  </view>
</template>

<script>
import { mapState, mapMutations, mapActions, mapGetters } from "vuex";
// import UToast from "../../../dist/dev/app-plus/static/style/uview-ui/components/u-toast/u-toast.vue";
export default {
  name: "order-card",
  props: {
    // list: {
    //   type: Object,
    //   default: () => {
    //     return {};
    //   },
    list: {
      type: Array,
      default: function () {
        return [];
      },
    },
    keyname: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      footStyle: {
        padding: "0",
      },
      cart: [], // storage.

      // 业务相关
    };
  },
  //   onLoad(){
  //       this.init();
  //   },
  onReady() {
    // this.init();
    // console.log("ready");
  },
  created() {
    console.log("created");
    this.init();
  },
  components: {
    // UToast,
  },
  computed: {
    // card title
    ...mapGetters(["getProduct"]),
    OrderItemImg() {
      // 获取 img
      // 从 全局
      return (id) => {
        return this.getProduct(id).defaultImg;
      };
    },
    cardTitle() {
      return (order) => {
        //   return `${order.id}`
        return `${order.receiverName}的订单`;
      };
    },
    cardSubTitle() {
      return (order) => {
        if (order.refundStatus == 1) {
          // 订单退款状态 0 || 1
          return "已退款";
        } else {
          if (order.confirmStatus == 1) {
            // 订单确认状态  （用户） 0 || 1
            return "已确认收货";
          } else {
            // 订单状态
            return order.orderStatusChinese;
          }
        }

        // return /
      };
    },
    cardBody() {
      return (order) => {
        if (order.orderItemList.length > 1) {
          return `${order.orderItemList[0].productName}...等${order.orderItemList.length}件商品`;
        }
        return `${order.orderItemList[0].productName}...${order.orderItemList.length}件商品`;
      };
    },
  },
  methods: {
    init() {},
    handlerGoToMenu() {
      console.log("点单.");
      uni.switchTab({ url: "/pages/menu/menu" });
    },
    // 去付款
    handlerGoPay(order) {
      // 传递一个 order.orderSn
      // console.log("123123123123");
      uni.navigateTo({
        url: "../../pages/pay/alipay?sn=" + order.orderSn,
      });
    },
    // 订单送达
    handlerOverOrder(order) {
      console.log(order);
      let that = this;
      that.$u.api
        .overOrder({
          sn: order.orderSn,
        })
        .then((res) => {
          if ((res.code = 0)) {
          } else {
            // that.$refs.tips.show({
            //   title: "稍后重试",
            //   type: "error",
            // });
            // that.handerRefreshChild();
          }
        });

      that.$refs.tips.show({
        title: "确认收货",
        type: "success",
      });
      that.handerRefreshChild();
    },
    // 触发父组件更新
    handerRefreshChild() {
      this.$emit("handerRefresh");
    },
    // 评价订单
    handlerCommit(order) {
      console.log(order);
      uni.navigateTo({
        url: "../../pages/orders/order-detail?sn=" + order.orderSn,
      });
    },

    // 申请售后
    handerApplyAfterSale(order) {
      uni.navigateTo({
        url: "../../pages/afterSale/afterSale?sn=" + order.orderSn,
      });
    },
    // 再来一单
    handlerMoreOne(order) {
      // todo ：
      let that = this;
      // let cart = []
      that.cart = [];
      console.log(order);
      // return ;
      // todo 添加 销售属性

      order.orderItemList.forEach((good) => {
        // const _ProductSaleAttrList = that.getProduct(good.productId);
        // console.log(_ProductSaleAttrList);
        // const _PropsContent = _ProductSaleAttrList.find(
        //   (s) => s.extraPrice == order.saleAttrExtraPrice
        // );
        // console.log(_PropsContent);
        console.log(good);
        // 销售属性 —— >  [number,number]
        let _saleIdTemp = good.saleAttrIdArray.length
        ? good.saleAttrIdArray.substr(0,good.saleAttrIdArray.length-1).split(';')
        : []
        if(good.saleAttrIdArray.length){
          //  _saleIdTemp.forEach(e=>{
            //  = parseInt(e)
          // })
          for(let i=0;i<_saleIdTemp.length;i++){
            _saleIdTemp[i] = parseInt(_saleIdTemp[i])
          }
        }
        // 添加到购物车
        that.cart.push({
          name: good.productName,
          id: good.productId,
          number: good.num,
          content: good.description, 
          defaultImg: good.defaultImg, // api无返回
          props_text: good.saleAttrValueArray , //
          props: _saleIdTemp,
          // price: order.realAmount / good.num ,
          price: good.basePrice + good.saleAttrExtraPrice,
        });
      });

      // uni.setStorageSync("cart", JSON.parse(JSON.stringify(that.cart)));
      console.log(that.cart);
      // uni.setStorageSync("cart", "");
      uni.removeStorage({
        key: "cart-" + that.$store.state.member.userId,
      });
      uni.setStorageSync(
        "cart-" + that.$store.state.member.userId,
        JSON.parse(JSON.stringify(this.cart))
      );
      // return;
      this.$store.commit('SET_SHOWMODEL',true)
      uni.switchTab({
            url: '/pages/menu/menu'
        });
    },

    // 退款
    async handlerCancel(order) {
      let params = { sn: order.orderSn };
      await this.$u.api.cancelOrder(params);
      // 触发父组件更新
      this.handerRefreshChild();
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/pages/pay/pay.scss";
.order_no {
  // display: flex;
  height: 100vh;
  box-sizing: border-box;
  padding-top: 200rpx;
  //   background: black;
  position: relative;
  .up {
    display: flex;
    text-align: center;
    justify-content: center;
    width: 100%;
    // background: blue;
    padding: 20rpx;
    .highlight {
      // font-size:;
      color: $uni-color-primary;
    }
  }
  .down {
    position: absolute;
    bottom: 350rpx;
    display: flex;
    text-align: center;
    // background: #fff;
    justify-content: space-around;
    flex-direction: column;
    align-content: center;
    align-items: center;
    width: 100%;
    height: 120rpx;
  }
}

.order {
  //   height: 100%;
  padding-bottom: 20px;

  .foot_btn {
    // background: red;
    display: flex;
    justify-content: flex-end;
    padding: 10rpx;
    button {
      display: inline-block;
      background: #fff;
      border: none;
      font-size: $uni-font-size-mm;
    }
    // .btn_to_pay {
    //   margin-right: 10rpx;
    //   &:active {
    //     background: #4cd964;
    //     color: #fff;
    //     border: 1px solid #4cd964;
    //   }
    // }
    .btn_cancel {
      box-sizing: border-box;
      border: 1px solid black;
      &:active {
        background: red;
        border: 1px solid red;
        color: #fff;
      }
    }
    .over {
      color: #4cd964;
      border: 1px solid #4cd964;
      &:active {
        background: #4cd964;
        color: #fff;
        border: 1px solid #4cd964;
      }
      margin-right: 10rpx;
    }
    .moreOne,
    .btn_to_pay {
      color: $uni-color-primary;
      border: 1px solid $uni-color-primary;
      margin-right: 10rpx;
      &:active {
        background: $uni-color-primary;
        color: #fff;
        border: 1px solid $uni-color-primary;
      }
      margin-right: 10rpx;
    }
    .commit {
      color: #f0ad4e;
      border: 1px solid #f0ad4e;
      &:active {
        background: #f0ad4e;
        color: #fff;
        border: 1px solid #f0ad4e;
      }
    }
    .after_sale {
      color: red;
      border: 1px solid red;
      &:active {
        background: red;
        color: #fff;
        border: 1px solid red;
      }
    }
  }
  .end {
    text-align: center;
    width: 100%;
  }
}
</style>
